import { _decorator, geometry, Node, Vec3, Color, renderer, Camera, MeshRenderer } from 'cc';
import { Debug } from '../Phyic/core/Debug';
import { aa } from '../frame/FrameCore';
import { ui } from '../frame/common/Enums';
import { NodeCtrl } from './NodeCtrl';

export class HitCtrl {
    nodeCtrlView: Node = null;
    private _ctrlNode: Node = null;
    public aabbScale: Vec3 = new Vec3(0.15, 0.15, 0.15);
    // 存储当前高亮的节点
    private currentHighlightedNode: Node | null = null;
    hitMap: Map<Node, renderer.scene.Model> = new Map();
    highlightColor: Color = Color.CYAN;
    static ins: HitCtrl;

    private _tempWorldPos: Vec3 = new Vec3();
    private _tempScreenPos: Vec3 = new Vec3();
    private _tempUIPos: Vec3 = new Vec3();
    addTest(testNode) {
        if (testNode) {
            const children = testNode.children;
            children.forEach(child => {
                const mesh = child.getComponent(MeshRenderer);
                if (mesh) {
                    this.hitMap.set(child, mesh.model);
                }
            })
        }
    }


    async setNodeCtrl(node: Node) {
        if (!this.nodeCtrlView) {
            this.nodeCtrlView = await aa.ui.get(ui.NodeCtrl)

        }
        const ctrl = this.nodeCtrlView.getComponent(NodeCtrl);
        ctrl.ctrlNode = this._ctrlNode = node;
    }
    clearClick(node?) {
        if (node) {
            node = this._ctrlNode;
        }
        this.hitMap.delete(node);
        this._ctrlNode = null;
        aa.ui.put(ui.NodeCtrl)

        this.nodeCtrlView = null;

    }

    clearNodeCtrl(node: Node) {
        this.clearClick(node);
        node && node.destroy();



    }
    deleteNode() {
        if (this._ctrlNode) {
            this._ctrlNode.destroy();
        }
    }
    rotateNode() {
        if (this._ctrlNode) {
            const y = this._ctrlNode.eulerAngles.y;
            this._ctrlNode.setRotationFromEuler(0, y - 90, 0);
        }
    }
    // 3D世界坐标转换为2D UI坐标
    private worldToUIPosition(worldPos: Vec3): Vec3 {

        // 1. 世界坐标转屏幕坐标
        aa.global.cameras[1].worldToScreen(worldPos, this._tempScreenPos);
        // 2. 屏幕坐标转UI坐标
        aa.global.cameras[0].screenToWorld(this._tempScreenPos, this._tempUIPos);
        // 3. 应用偏移
        this._tempUIPos.y += 60;
        return this._tempUIPos;
    }


    // 更新UI位置
    private updateUIPosition() {
        if (!this.nodeCtrlView) {
            return;
        }
        // 获取3D节点的世界位置
        this._ctrlNode.getWorldPosition(this._tempWorldPos);
        // 可以选择节点顶部位置作为UI跟随点
        const hitInfo = this.hitMap.get(this._ctrlNode);
        if (hitInfo) {
            const bounds = hitInfo.worldBounds;
            this._tempWorldPos.y = bounds.center.y + bounds.halfExtents.y; // 使用边界框顶部
        }

        // 转换为UI坐标并设置位置
        const uiPos = this.worldToUIPosition(this._tempWorldPos);
        this.nodeCtrlView.setWorldPosition(uiPos);
    }
    lateUpdate() {

        this.updateUIPosition();
        if (this.currentHighlightedNode) {
            this.drawNodeBorder(this.currentHighlightedNode, this.highlightColor);
        }

    }

    // 设置高亮节点
    public setHighlightNode(node: Node | null, color: Color = this.highlightColor) {
        this.currentHighlightedNode = node;
        this.highlightColor = color;
    }
    public addNode(node: Node, mesh: MeshRenderer) {

        // 获取模型的本地边界框
        const modelComp = mesh.model;
        if (!modelComp) {
            console.warn("Mesh component not found");
            return;
        }
        // 添加到hitMap
        this.hitMap.set(node, modelComp);
        this.setNodeCtrl(node)
        this.currentHighlightedNode = node;
        this.highlightColor = Color.YELLOW;


    }

    // 显示节点边框（设置高亮状态）
    public showNodeBorder(node: Node, color: Color = this.highlightColor) {
        this.setHighlightNode(node, color);
    }

    // 实际绘制边框的方法
    private drawNodeBorder(node: Node, color: Color) {
        const hitInfo = this.hitMap.get(node);
        if (!hitInfo) {
            return;
        }
        // 直接使用worldBounds，它本身就是AABB
        const worldBounds = hitInfo.worldBounds;
        Debug.addAABB(worldBounds, color);
    }

    // 清除高亮边框
    public clearHighlight() {
        this.currentHighlightedNode = null;
    }
    // 新增：检查射线是否击中任何物体，并高亮显示
    public checkRayHit(ray: geometry.Ray): Node | null {
        let hitNode: Node | null = null;
        let minDistance = 1000;
        this.hitMap.forEach((value, node) => {
            // 这里可以复用OrbitCamera中的_checkBound方法逻辑
            const result = this._checkBound(ray, node, value);
            // console.log("hit result=="+result.dist)
            if (result != 0 && result < minDistance) {
                hitNode = node;
                minDistance = result;
            }
        });
        // 高亮最近的物体
        if (hitNode) {
            this.showNodeBorder(hitNode, Color.WHITE);
        } else {
            this.clearHighlight();
        }

        return hitNode;
    }

    // 复用OrbitCamera中的边界检测逻辑
    private _checkBound(ray: geometry.Ray, node: Node, model: renderer.scene.Model): number {
        if (!model) return;

        // 直接使用worldBounds
        const worldBounds = model.worldBounds;
        const res = geometry.intersect.rayAABB(ray, worldBounds);
        return res;
    }
}
const HIT = new HitCtrl;
export default HIT;